//
//  KABMallReturnProVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/21.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallReturnProVC.h"
#import "SZTextView.h"
#import "KABCosPublishCCell.h"
#import "KABCosPublishCRView.h"
#import "KABCosPubEditVC.h"
#import "KABModel.h"
#import <TZImagePickerController.h>
#import <TZImageManager.h>
#import "MBProgressHUD+XDPrompt.h"
#import "XDQiniuManager.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "XDAFNetworking.h"

@interface KABMallReturnProVC ()<UICollectionViewDelegate, UICollectionViewDataSource, KABCosPublishCCellDelegate, TZImagePickerControllerDelegate, UITextViewDelegate>

@property (weak, nonatomic) IBOutlet SZTextView *szTextView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

@property (nonatomic, strong) KABCosPublishModel *pubModel;

@end

static NSString *const kReuseCellId = @"KABCosPublishCCell";
static NSString *const kReuseCRViewId = @"KABCosPublishCRView";
static NSInteger const kMaxPictureCnt = 3;

@implementation KABMallReturnProVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"申请退货";
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(publishBarBtnTapped:)];
}

- (void)initSubViews {
    self.szTextView.delegate = self;
    
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:kReuseCellId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.submitBtn.layer.masksToBounds = YES;
    self.submitBtn.layer.cornerRadius = CGRectGetHeight(self.submitBtn.bounds) / 2.0;
    [self.submitBtn addTarget:self action:@selector(submitBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshWholeView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return (self.pubModel.cosplay_detail.count < kMaxPictureCnt) ? self.pubModel.cosplay_detail.count + 1 : kMaxPictureCnt;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KABCosPublishCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseCellId forIndexPath:indexPath];
    KABCosPublishItem *item = nil;
    if (indexPath.row < self.pubModel.cosplay_detail.count) {
        item = self.pubModel.cosplay_detail[indexPath.row];
    }
    [cell configViewWithPublishItem:item];
    cell.delegate = self;
    return cell;
}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABCosPublishCRView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseCRViewId forIndexPath:indexPath];
//        header.pubModel = self.pubModel;
//        return header;
//    }
//    return nil;
//}

#pragma mark - <UICollectionViewDelegateFlowLayout>
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 110.0);
//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (CGRectGetWidth(self.view.bounds) - 2*13 - 2 * 24) / 3.0;
    return CGSizeMake(width, width);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.pubModel.cosplay_detail.count) {
        ;
    } else {
        // 添加照片
        NSInteger maxCnt = kMaxPictureCnt - self.pubModel.cosplay_detail.count;
        TZImagePickerController * pickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCnt delegate:self];
        pickerVC.allowPickingVideo = NO;
        pickerVC.allowTakePicture = NO;
        pickerVC.allowPickingOriginalPhoto = NO;
        [self presentViewController:pickerVC animated:YES completion:nil];
    }
}

#pragma mark - KABCosPublishCCellDelegate
- (void)KABCosPublishCCell:(KABCosPublishCCell *)cell deleteBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    [self.pubModel removePublishItemAtIndex:indexPath.row];
    if (indexPath.row == kMaxPictureCnt - 1) {
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    } else {
        if (self.pubModel.cosplay_detail.count == kMaxPictureCnt - 1) {
            [self refreshWholeView];
        } else {
            [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
        }
    }
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    if (isSelectOriginalPhoto) {
        [assets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            [[TZImageManager manager] getOriginalPhotoWithAsset:obj newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
//                NSLog(@"获取原图%@， --%@, (%zd)", photos, info, isDegraded);
//                if (!isDegraded) {
//                    [self.pubModel addPublishItemsWithArray:@[photo]];
//                    [self refreshWholeView];
//                }
//            }];
            
            // 上面一个占用内存太大，导致崩溃。所以只能考虑下面这个获取原图的方法。
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:obj completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                NSLog(@"获取原图--%@, (%zd)", info, isDegraded);
                if (!isDegraded) {
                    if (idx < photos.count) {
                        [self.pubModel addPublishItemsWithImgArray:@[photos[idx]] originalDataArray:@[data]];
                        [self refreshWholeView];
                    }
                }
            }];
        }];
    } else {
        [self.pubModel addPublishItemsWithImgArray:photos originalDataArray:nil];
        [self refreshWholeView];
    }
}

//- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
//    NSLog(@"选择照片缩略图 = %@", photos);
//    NSLog(@"选择照片原始的assets = %@", assets);
//    NSLog(@"选取照片之后的infos = %@", infos);
//}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {    
    NSString *toBeString = textView.text;
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position || !selectedRange) {
        if (toBeString.length > KABGlobalReturnProReasonLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:KABGlobalReturnProReasonLength];
            if (rangeIndex.length == 1) {
                textView.text = [toBeString substringToIndex:KABGlobalReturnProReasonLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, KABGlobalReturnProReasonLength)];
                textView.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
    
    self.pubModel.top_content = textView.text;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    self.pubModel.top_content = textView.text;
}

#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
//    if (self.pubModel.isEmpty) {
//        [self dismissViewControllerAnimated:YES completion:nil];
//    } else {
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"离开发布页后，编辑内容将被清空" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
//        [alertVC addAction:[UIAlertAction actionWithTitle:@"离开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [self dismissViewControllerAnimated:YES completion:nil];
//        }]];
//        [self presentViewController:alertVC animated:YES completion:nil];
//    }
}

- (void)submitBtnTapped:(UIButton *)btn {
    if (!self.pubModel.top_content.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入退货原因"];
        return;
    }
    
    // 没有图片的话，直接请求退货接口
    if (!self.pubModel.cosplay_detail.count) {
        [self requestReturnProduct];
        return;
    }
    
    // 图片上传成功、发布未成功的情况下，直接去发布即可
    if (self.pubModel.isImgUpload) {
        [self requestReturnProduct];
        return;
    }
    
    // 上传图片
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.label.text = @"上传图片...";
    [[XDQiniuManager sharedInstance] uploadImages:self.pubModel.imgArray progress:^(NSString *key, float percent) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = percent;
        });
    } success:^(NSArray<NSString *> *urlArray) {
        [hud hideAnimated:NO];
        [self.pubModel updateImgUrlWithArray:urlArray];
        // 发表到服务器
        [self requestReturnProduct];
        NSLog(@"开始发表到服务器");
    } failure:^(NSString *error) {
        NSLog(@"上传图片失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:error];
    }];
}

#pragma mark - private methods
- (void)refreshWholeView {
    [self.collectionView reloadData];
}

- (void)exitViewController {
    if (self.returnSucHandle) {
        self.returnSucHandle();
        self.returnSucHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestReturnProduct {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 发布帖子
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"image_list" : self.pubModel.urlArray,
                           @"reason" : self.pubModel.top_content,
                           @"order_id" : self.orderDetail.order_id};
    NSLog(@"申请退货的参数：%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCancelOrder] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"申请退货返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            temp.completionBlock = ^(){
                [self exitViewController];
            };
        } else {
            ;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"申请退货失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (KABCosPublishModel *)pubModel {
    if (!_pubModel) {
        _pubModel = [[KABCosPublishModel alloc] init];
    }
    return _pubModel;
}

@end
